import 'package:flutter/material.dart';
import '../config/config.dart';
import '../utils/HttpRequest.dart';

class ProfilePage extends StatefulWidget {
  const ProfilePage({super.key});

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _tokenController = TextEditingController();
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GitCodeApiClient _client = GitCodeApiClient();

  String? _username;
  String? _token;
  GitCodeUser? _userInfo;
  List<GitCodeRepository> _userRepos = [];
  bool _isLoading = false;
  bool _isLogin = false;
  String? _errorMessage;
  bool _obscureToken = true;

  @override
  void initState() {
    super.initState();
    // 初始化token为配置文件中的默认值
    _tokenController.text = AppConfig.demoToken;
  }

  @override
  void dispose() {
    _usernameController.dispose();
    _tokenController.dispose();
    super.dispose();
  }

  // 处理登录逻辑
  Future<void> _handleLogin() async {
    if (!_formKey.currentState!.validate()) return;

    FocusScope.of(context).unfocus();
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    _username = _usernameController.text.trim();
    _token = _tokenController.text.trim();

    try {
      // 调用API获取用户信息
      final userInfo = await _client.fetchUser(
        _username!,
        personalToken: _token!,
      );
      
      setState(() {
        _userInfo = userInfo;
        _isLogin = true;
      });

      // 登录成功后获取用户仓库
      _fetchUserRepositories();
    } on GitCodeApiException catch (error) {
      setState(() {
        _errorMessage = error.message;
      });
    } catch (error) {
      setState(() {
        _errorMessage = '未知错误：$error';
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  // 获取用户仓库列表
  Future<void> _fetchUserRepositories() async {
    if (_username == null || _token == null) return;

    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      final repos = await _client.getUserRepositories(
        username: _username!,
        personalToken: _token!,
        perPage: 20,
      );
      setState(() {
        _userRepos = repos;
      });
    } on GitCodeApiException catch (error) {
      setState(() {
        _errorMessage = error.message;
      });
    } catch (error) {
      setState(() {
        _errorMessage = '获取仓库失败：$error';
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  // 处理登出
  void _handleLogout() {
    setState(() {
      _isLogin = false;
      _userInfo = null;
      _userRepos = [];
      _username = null;
      _token = null;
      _usernameController.clear();
      _tokenController.text = AppConfig.demoToken;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('个人页面'),
        actions: _isLogin
            ? [
                IconButton(
                  icon: const Icon(Icons.refresh),
                  onPressed: _fetchUserRepositories,
                ),
                IconButton(
                  icon: const Icon(Icons.logout),
                  onPressed: _handleLogout,
                ),
              ]
            : [],
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(20),
          child: _isLogin ? _buildProfileContent() : _buildLoginForm(),
        ),
      ),
    );
  }

  // 登录表单
  Widget _buildLoginForm() {
    return Card(
      elevation: 0,
      clipBehavior: Clip.antiAlias,
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              const Text(
                '请输入用户名和授权码登录',
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 20),
              TextFormField(
                controller: _usernameController,
                decoration: const InputDecoration(
                  labelText: '用户名',
                  hintText: '输入GitCode用户名',
                  prefixIcon: Icon(Icons.person),
                ),
                validator: (value) {
                  if (value == null || value.trim().isEmpty) {
                    return '请输入用户名';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 12),
              TextFormField(
                controller: _tokenController,
                decoration: InputDecoration(
                  labelText: '授权码',
                  hintText: 'GitCode个人设置 > Access Token',
                  prefixIcon: const Icon(Icons.vpn_key_outlined),
                  suffixIcon: IconButton(
                    icon: Icon(
                      _obscureToken
                          ? Icons.visibility_off_outlined
                          : Icons.visibility_outlined,
                    ),
                    onPressed: () {
                      setState(() {
                        _obscureToken = !_obscureToken;
                      });
                    },
                  ),
                ),
                obscureText: _obscureToken,
                validator: (value) {
                  if (value == null || value.trim().isEmpty) {
                    return '请输入授权码';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 20),
              if (_errorMessage != null)
                Padding(
                  padding: const EdgeInsets.only(bottom: 12),
                  child: _InfoBanner(
                    icon: Icons.error_outline,
                    background: Colors.red.withOpacity(0.08),
                    textColor: Colors.red.shade700,
                    message: _errorMessage!,
                  ),
                ),
              FilledButton.icon(
                onPressed: _isLoading ? null : _handleLogin,
                icon: _isLoading
                    ? const SizedBox(
                        width: 18,
                        height: 18,
                        child: CircularProgressIndicator(strokeWidth: 2),
                      )
                    : const Icon(Icons.login),
                label: Text(_isLoading ? '登录中...' : '登录'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 个人信息和仓库列表内容
  Widget _buildProfileContent() {
    if (_userInfo == null) {
      return const Center(child: Text('用户信息加载失败'));
    }

    return Column(
      children: [
        // 用户信息卡片
        Card(
          elevation: 0,
          clipBehavior: Clip.antiAlias,
          child: Padding(
            padding: const EdgeInsets.all(20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                CircleAvatar(
                  radius: 50,
                  backgroundImage: NetworkImage(_userInfo!.avatarUrl),
                  onBackgroundImageError: (_, __) {},
                ),
                const SizedBox(height: 16),
                Text(
                  _userInfo!.name ?? _userInfo!.login ?? '未知用户',
                  style: const TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 8),
                Text(
                  '@${_userInfo!.login}',
                  style: const TextStyle(fontSize: 16, color: Colors.grey),
                ),
                const SizedBox(height: 12),
                if (_userInfo!.bio != null && _userInfo!.bio!.isNotEmpty)
                  Text(
                    _userInfo!.bio!,
                    textAlign: TextAlign.center,
                    style: const TextStyle(fontSize: 14),
                  ),
                const SizedBox(height: 16),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    _StatItem(
                      label: '仓库',
                      value: _userInfo!.publicRepos ?? 0,
                    ),
                    _StatItem(
                      label: '关注者',
                      value: _userInfo!.followers ?? 0,
                    ),
                    _StatItem(
                      label: '关注',
                      value: _userInfo!.following ?? 0,
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
        const SizedBox(height: 20),
        // 仓库列表标题
        const Text(
          '我的仓库',
          style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
        ),
        const SizedBox(height: 12),
        // 仓库列表
        _buildRepositoryList(),
      ],
    );
  }

  // 仓库列表
  Widget _buildRepositoryList() {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_errorMessage != null) {
      return _InfoBanner(
        icon: Icons.error_outline,
        background: Colors.red.withOpacity(0.08),
        textColor: Colors.red.shade700,
        message: _errorMessage!,
      );
    }

    if (_userRepos.isEmpty) {
      return const _InfoBanner(
        icon: Icons.info_outline,
        background: Color(0xFFEFF4FF),
        textColor: Color(0xFF1A237E),
        message: '暂无仓库数据',
      );
    }

    return Column(
      children: _userRepos.map(_RepoTile.new).toList(),
    );
  }
}

// 信息横幅组件
class _InfoBanner extends StatelessWidget {
  const _InfoBanner({
    required this.icon,
    required this.background,
    required this.textColor,
    required this.message,
  });

  final IconData icon;
  final Color background;
  final Color textColor;
  final String message;

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: background,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Icon(icon, color: textColor),
          const SizedBox(width: 12),
          Expanded(
            child: Text(
              message,
              style: Theme.of(context)
                  .textTheme
                  .bodyMedium
                  ?.copyWith(color: textColor),
            ),
          ),
        ],
      ),
    );
  }
}

// 统计数据项
class _StatItem extends StatelessWidget {
  const _StatItem({required this.label, required this.value});

  final String label;
  final int value;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text(
          value.toString(),
          style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
        ),
        Text(
          label,
          style: const TextStyle(fontSize: 14, color: Colors.grey),
        ),
      ],
    );
  }
}

// 仓库信息卡片组件
class _RepoTile extends StatelessWidget {
  const _RepoTile(this.repo);

  final GitCodeRepository repo;

  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 0,
      margin: const EdgeInsets.only(bottom: 12),
      child: ListTile(
        leading: const Icon(Icons.folder_outlined),
        title: Text(repo.fullName, style: const TextStyle(fontWeight: FontWeight.w600)),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (repo.description?.isNotEmpty == true)
              Padding(
                padding: const EdgeInsets.only(bottom: 4),
                child: Text(
                  repo.description!,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            Wrap(
              spacing: 8,
              runSpacing: 4,
              children: [
                if (repo.language != null)
                  _StatChip(label: '语言', valueLabel: repo.language),
                _StatChip(label: 'Star', value: repo.stars),
                _StatChip(label: 'Fork', value: repo.forks),
              ],
            ),
            const SizedBox(height: 4),
            Text(
              '更新 ${repo.updatedAt ?? '-'}',
              style: const TextStyle(fontSize: 12),
            ),
          ],
        ),
      ),
    );
  }
}

// 统计信息标签组件
class _StatChip extends StatelessWidget {
  const _StatChip({required this.label, this.value, this.valueLabel});

  final String label;
  final int? value;
  final String? valueLabel;

  @override
  Widget build(BuildContext context) {
    final textTheme = Theme.of(context).textTheme;
    final display = valueLabel ?? (value ?? 0).toString();
    return Chip(
      label: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            display,
            style: textTheme.titleMedium,
          ),
          Text(label, style: textTheme.bodySmall),
        ],
      ),
    );
  }
}